package com.haochu.xxl.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.haochu.xxl.R;
import com.haochu.xxl.map.MapUtil;
import com.haochu.xxl.model.PointItem;
import com.haochu.xxl.util.BackgroundMusic;
import com.haochu.xxl.util.Constants;
import com.haochu.xxl.util.MeasureUtil;

@SuppressLint({"ClickableViewAccessibility", "ShowToast"})
public class GameSceneActivity extends Activity implements OnTouchListener, OnClickListener {

    // 游戏主界面view
    private GameSceneView mGameSceneView;
    // 吐司
    private Toast mToast;
    // 屏幕尺寸
    private int screenWidth, screenHeight;
    // 点击时的坐标
    private float x, y;
    // 移动时的坐标
    private float xmove, ymove;
    // 点击对应的元素点
    private PointItem p1 = null, p2 = null;
    // 背景音乐
    private BackgroundMusic bgMusic;
    // 游戏音效
    private SoundPool soundPool;
    // 连续消除时的音效
    private Integer[] soundPoolArrayRemove = null;
    // 连续消除后的音效
    private Integer[] soundPoolArrayContinue = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // 初始化系统常量
        initConstants();

        setContentView(R.layout.game_scene);

        // 开始播放背景音乐
        bgMusic = BackgroundMusic.getInstance(this);
        bgMusic.playBackgroundMusic(Constants.bgmGameScene, true);

        // 初始化游戏音效
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        // 连续消除时的音效
        soundPoolArrayRemove = new Integer[8];
        soundPoolArrayRemove[0] = soundPool.load(this, R.raw.remove1, 1);
        soundPoolArrayRemove[1] = soundPool.load(this, R.raw.remove2, 1);
        soundPoolArrayRemove[2] = soundPool.load(this, R.raw.remove3, 1);
        soundPoolArrayRemove[3] = soundPool.load(this, R.raw.remove4, 1);
        soundPoolArrayRemove[4] = soundPool.load(this, R.raw.remove5, 1);
        soundPoolArrayRemove[5] = soundPool.load(this, R.raw.remove6, 1);
        soundPoolArrayRemove[6] = soundPool.load(this, R.raw.remove7, 1);
        soundPoolArrayRemove[7] = soundPool.load(this, R.raw.remove8, 1);

        // 连续消除后的音效
        soundPoolArrayContinue = new Integer[6];
        soundPoolArrayContinue[0] = null;
        soundPoolArrayContinue[1] = soundPool.load(this, R.raw.continue1, 1);
        soundPoolArrayContinue[2] = soundPool.load(this, R.raw.continue2, 1);
        soundPoolArrayContinue[3] = soundPool.load(this, R.raw.continue3, 1);
        soundPoolArrayContinue[4] = soundPool.load(this, R.raw.continue4, 1);
        soundPoolArrayContinue[5] = soundPool.load(this, R.raw.continue5, 1);

        // 初始化吐司
        mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);

        // 监听触摸操作
        mGameSceneView = findViewById(R.id.mGameSceneView);
        mGameSceneView.setOnTouchListener(this);
        mGameSceneView.setSoundPool(soundPool);
        mGameSceneView.setSoundPoolArrayRemove(soundPoolArrayRemove);
        mGameSceneView.setSoundPoolArrayContinue(soundPoolArrayContinue);
        mGameSceneView.setScreenWidth(screenWidth);
        mGameSceneView.setScreenHeight(screenHeight);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!mGameSceneView.isAnimationEnd()) {
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            xmove = event.getX();
            ymove = event.getY();
            // 当移动出当前元素点，才开始判断
            PointItem point = mGameSceneView.getPointByTouch(xmove, ymove);
            if (p1 != null && point != null && point != p1 && (point.nextX(p1) || point.nextY(p1))) {
                // 交换
                mGameSceneView.change(point, p1, true);
                p1 = null;
                selectPoint(p1);
                return true;
            }
        } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
            x = event.getX();
            y = event.getY();

            // 获取点击的位置对应的元素点，若没有则无效
            PointItem point = mGameSceneView.getPointByTouch(x, y);
            if (point == null) {
                return true;
            }
            if (p1 == null) {
                p1 = point;
            } else {
                p2 = point;
                // 判断两次点击的点是否相邻
                if (p1.nextX(p2) || p1.nextY(p2)) {
                    // 交换
                    mGameSceneView.change(p1, p2, true);
                    p1 = null;
                } else {
                    p1 = point;
                }
                p2 = null;
            }
            selectPoint(p1);
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mGameSceneView.invalidate();
                    break;
                case 1:
                    mGameSceneView.checkAndRemove();
                    mGameSceneView.invalidate();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 选中状态
     */
    public void selectPoint(PointItem point) {
        mGameSceneView.setPointChecked(point);
        mHandler.sendEmptyMessage(0);
    }

    /**
     * 初始化常量
     */
    public void initConstants(){
        // 获取屏幕尺寸
        screenWidth = MeasureUtil.getScreenWidth(this);
        screenHeight = MeasureUtil.getScreenHeight(this);

        // 初始化每一个元素的尺寸
        Constants.SIZE = (screenWidth - Constants.MARGIN_LEFT - Constants.MARGIN_RIGHT) / 8;
        Constants.MARGIN_TOP = (screenHeight - MapUtil.map_1.length * Constants.SIZE) / 2;

        // 初始化工具栏气泡宽度
        Constants.WIDTH_BUBBLE = (int) (screenWidth - Constants.MARGIN_TOOL_LEFT - Constants.MARGIN_TOOL_RIGHT - 4 * Constants.PADDING_TOOL) / 5;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 结束背景音乐
        bgMusic.end();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 暂停背景音乐
        bgMusic.pauseBackgroundMusic();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 继续背景音乐
        bgMusic.resumeBackgroundMusic();
    }
}
